<template>
  <div class="change-password-page page-container">
    <!-- 顶部导航 -->
    <van-nav-bar
      title="修改密码"
      left-arrow
      @click-left="router.back()"
    >
      <template #left>
        <van-icon name="arrow-left" size="18" />
      </template>
    </van-nav-bar>

    <div class="content-container">
      <!-- 加载状态 -->
      <van-overlay :show="loading" class="loading-overlay">
        <van-loading type="spinner" color="#4080ff" />
      </van-overlay>

      <!-- 安全提示 -->
      <div class="security-tips">
        <van-icon name="info-o" size="20" />
        <span>为保证账号安全，请定期修改密码</span>
      </div>

      <!-- 表单内容 -->
      <div class="form-section">
        <van-cell-group inset>
          <van-field
            v-model="passwordForm.oldPassword"
            label="当前密码"
            placeholder="请输入当前密码"
            type="password"
            :rules="[{ required: true, message: '请输入当前密码' }]"
          >
            <template #left-icon>
              <van-icon name="lock" class="field-icon" />
            </template>
            <template #right-icon>
              <van-icon 
                :name="showOldPassword ? 'eye-o' : 'closed-eye'" 
                class="eye-icon" 
                @click="showOldPassword = !showOldPassword"
              />
            </template>
          </van-field>
          
          <van-field
            v-model="passwordForm.newPassword"
            label="新密码"
            placeholder="请输入新密码"
            :type="showNewPassword ? 'text' : 'password'"
            :rules="[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码长度不能少于6位' }
            ]"
          >
            <template #left-icon>
              <van-icon name="passed" class="field-icon" />
            </template>
            <template #right-icon>
              <van-icon 
                :name="showNewPassword ? 'eye-o' : 'closed-eye'" 
                class="eye-icon" 
                @click="showNewPassword = !showNewPassword"
              />
            </template>
          </van-field>
          
          <van-field
            v-model="passwordForm.confirmPassword"
            label="确认密码"
            placeholder="请再次输入新密码"
            :type="showConfirmPassword ? 'text' : 'password'"
            :rules="[
              { required: true, message: '请确认新密码' },
              { validator: validateConfirmPassword, message: '两次输入的密码不一致' }
            ]"
          >
            <template #left-icon>
              <van-icon name="checked" class="field-icon" />
            </template>
            <template #right-icon>
              <div class="right-icon-container">
                <van-icon 
                  v-if="passwordMismatch" 
                  name="warning-o" 
                  class="warning-icon" 
                />
                <van-icon 
                  :name="showConfirmPassword ? 'eye-o' : 'closed-eye'" 
                  class="eye-icon" 
                  @click="showConfirmPassword = !showConfirmPassword"
                />
              </div>
            </template>
          </van-field>
        </van-cell-group>
      </div>

      <!-- 密码强度提示 -->
      <div class="password-strength" v-if="passwordForm.newPassword">
        <div class="strength-label">密码强度:</div>
        <div class="strength-bar">
          <div 
            class="strength-value" 
            :style="{ width: passwordStrength.percent + '%' }"
            :class="passwordStrength.level"
          ></div>
        </div>
        <div class="strength-text" :class="passwordStrength.level">
          {{ passwordStrength.text }}
        </div>
      </div>

      <!-- 密码提示 -->
      <div class="password-tips">
        <div class="tips-title">
          <van-icon name="warning-o" />
          <span>密码要求</span>
        </div>
        <ul class="tips-list">
          <li :class="{ active: passwordForm.newPassword.length >= 6 }">长度至少为6个字符</li>
          <li :class="{ active: /[A-Z]/.test(passwordForm.newPassword) }">包含大写字母</li>
          <li :class="{ active: /[a-z]/.test(passwordForm.newPassword) }">包含小写字母</li>
          <li :class="{ active: /[0-9]/.test(passwordForm.newPassword) }">包含数字</li>
          <li :class="{ active: /[^A-Za-z0-9]/.test(passwordForm.newPassword) }">包含特殊字符</li>
        </ul>
      </div>

      <!-- 错误提示区域 -->
      <div class="error-message" v-if="!isFormValid && formHasInput">
        <van-icon name="warning-o" />
        <span>{{ getFormErrorMessage() }}</span>
      </div>
      
      <!-- 提交按钮 -->
      <div class="action-section">
        <van-button 
          block 
          type="primary" 
          @click="handleChangePassword"
          :loading="changing"
          :disabled="!isFormValid"
          class="submit-btn"
        >
          确认修改
        </van-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showToast, showDialog } from 'vant';
import { useUserStore } from '@/stores/user';

const router = useRouter();
const userStore = useUserStore();

// 用户信息
const isLoggedIn = computed(() => userStore.isLoggedIn);

// 加载状态
const loading = ref(false);
const changing = ref(false);

// 密码显示控制
const showOldPassword = ref(false);
const showNewPassword = ref(false);
const showConfirmPassword = ref(false);

// 密码表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 表单验证
const validateConfirmPassword = () => {
  return passwordForm.value.newPassword === passwordForm.value.confirmPassword;
};

// 表单是否有效
const isFormValid = computed(() => {
  return (
    passwordForm.value.oldPassword.length > 0 &&
    passwordForm.value.newPassword.length >= 6 &&
    passwordForm.value.confirmPassword === passwordForm.value.newPassword
  );
});

// 密码不匹配检测
const passwordMismatch = computed(() => {
  return passwordForm.value.confirmPassword && 
         passwordForm.value.newPassword !== passwordForm.value.confirmPassword;
});

// 检查表单是否有输入
const formHasInput = computed(() => {
  return passwordForm.value.oldPassword || 
         passwordForm.value.newPassword || 
         passwordForm.value.confirmPassword;
});

// 获取表单错误信息
const getFormErrorMessage = () => {
  if (!passwordForm.value.oldPassword) {
    return '请输入当前密码';
  }
  if (!passwordForm.value.newPassword) {
    return '请输入新密码';
  }
  if (passwordForm.value.newPassword.length < 6) {
    return '新密码长度不能少于6位';
  }
  if (!passwordForm.value.confirmPassword) {
    return '请确认新密码';
  }
  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    return '两次输入的密码不一致';
  }
  return '';
};

// 计算密码强度
const passwordStrength = computed(() => {
  const password = passwordForm.value.newPassword;
  if (!password) {
    return { level: 'none', text: '无', percent: 0 };
  }
  
  let strength = 0;
  
  // 长度检查
  if (password.length >= 6) strength += 1;
  if (password.length >= 10) strength += 1;
  
  // 字符类型检查
  if (/[A-Z]/.test(password)) strength += 1;
  if (/[a-z]/.test(password)) strength += 1;
  if (/[0-9]/.test(password)) strength += 1;
  if (/[^A-Za-z0-9]/.test(password)) strength += 1;
  
  // 计算强度等级
  let level = 'weak';
  let text = '弱';
  let percent = 30;
  
  if (strength >= 3) {
    level = 'medium';
    text = '中';
    percent = 60;
  }
  
  if (strength >= 5) {
    level = 'strong';
    text = '强';
    percent = 100;
  }
  
  return { level, text, percent };
});

// 修改密码
const handleChangePassword = async () => {
  if (!isLoggedIn.value) {
    showToast('请先登录');
    router.push('/auth/login');
    return;
  }

  if (!isFormValid.value) {
    showToast(getFormErrorMessage());
    return;
  }

  changing.value = true;
  try {
    // 确保发送的数据格式与后端期望的一致
    const changePasswordData = {
      oldPassword: passwordForm.value.oldPassword,
      newPassword: passwordForm.value.newPassword,
      confirmPassword: passwordForm.value.confirmPassword // 添加确认密码字段
    };
    
    console.log('发送修改密码请求:', changePasswordData);
    
    // 直接调用 API 而不是通过 store
    const response = await userStore.changePassword(changePasswordData);
    
    console.log('修改密码响应:', response);
    
    // 显示确认对话框
    showDialog({
      title: '密码已修改',
      message: '密码修改成功，需要重新登录',
      confirmButtonText: '确定',
      showCancelButton: false,
      confirmButtonColor: '#4080ff'
    }).then(() => {
      // 退出登录并跳转到登录页
      userStore.logout();
      router.push('/auth/login');
    });
  } catch (error: any) {
    console.error('修改密码失败:', error);
    showToast(error.response?.data?.message || error.message || '修改密码失败，请检查当前密码是否正确');
  } finally {
    changing.value = false;
  }
};

// 页面加载时检查登录状态
onMounted(() => {
  if (!isLoggedIn.value) {
    showToast('请先登录');
    router.push('/auth/login');
  }
});
</script>

<style lang="scss" scoped>
.change-password-page {
  background-color: #f7f8fa;
  min-height: 100vh;

  .content-container {
    padding: 20px 16px;
  }

  .loading-overlay {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .security-tips {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    background-color: rgba(64, 128, 255, 0.08);
    border-radius: 12px;
    margin-bottom: 20px;
    
    .van-icon {
      color: #4080ff;
      margin-right: 8px;
    }
    
    span {
      font-size: 14px;
      color: #4080ff;
    }
  }

  .form-section {
    margin-bottom: 20px;

    :deep(.van-cell) {
      padding: 16px;
      align-items: center;
    }

    :deep(.van-field__label) {
      width: 80px;
      color: #333;
      font-weight: 500;
    }
    
    :deep(.van-cell-group--inset) {
      border-radius: 16px;
      overflow: hidden;
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
    }
    
    .field-icon {
      color: #4080ff;
      font-size: 18px;
      margin-right: 4px;
    }
    
    .eye-icon {
      color: #999;
      font-size: 18px;
      padding: 4px;
      
      &:active {
        opacity: 0.7;
      }
    }
    
    .right-icon-container {
      display: flex;
      align-items: center;
    }
  }
  
  .password-strength {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    padding: 0 4px;
    
    .strength-label {
      font-size: 14px;
      color: #666;
      margin-right: 10px;
      white-space: nowrap;
    }
    
    .strength-bar {
      flex: 1;
      height: 6px;
      background-color: #eee;
      border-radius: 3px;
      overflow: hidden;
      
      .strength-value {
        height: 100%;
        transition: width 0.3s ease;
        
        &.weak {
          background-color: #ff4d4f;
        }
        
        &.medium {
          background-color: #faad14;
        }
        
        &.strong {
          background-color: #52c41a;
        }
      }
    }
    
    .strength-text {
      margin-left: 10px;
      font-size: 14px;
      
      &.weak {
        color: #ff4d4f;
      }
      
      &.medium {
        color: #faad14;
      }
      
      &.strong {
        color: #52c41a;
      }
    }
  }
  
  .password-tips {
    background-color: #fff;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    
    .tips-title {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      
      .van-icon {
        color: #faad14;
        margin-right: 6px;
        font-size: 16px;
      }
      
      span {
        font-size: 15px;
        font-weight: 500;
        color: #333;
      }
    }
    
    .tips-list {
      margin: 0;
      padding-left: 20px;
      
      li {
        margin-bottom: 8px;
        color: #999;
        font-size: 14px;
        transition: color 0.3s;
        
        &.active {
          color: #52c41a;
          
          &::marker {
            color: #52c41a;
          }
        }
      }
    }
  }

  .warning-icon {
    color: #ff4d4f;
    font-size: 18px;
    margin-right: 4px;
  }

  .error-message {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    background-color: rgba(255, 77, 79, 0.1);
    border-radius: 8px;
    margin-bottom: 16px;
    
    .van-icon {
      color: #ff4d4f;
      margin-right: 6px;
    }
    
    span {
      font-size: 14px;
      color: #ff4d4f;
    }
  }

  .action-section {
    padding: 8px 0 24px;

    .submit-btn {
      height: 48px;
      border-radius: 12px;
      font-size: 16px;
      font-weight: 500;
      background: linear-gradient(135deg, #4080ff, #5e96ff);
      border: none;
      box-shadow: 0 6px 16px rgba(64, 128, 255, 0.3);
      transition: all 0.3s ease;

      &:active {
        transform: translateY(2px);
        box-shadow: 0 3px 8px rgba(64, 128, 255, 0.2);
      }
      
      &.van-button--disabled {
        opacity: 0.6;
        background: linear-gradient(135deg, #a6c1e6, #b8cce6);
      }
    }
  }
}
</style>
